package produce.boot;

import com.alibaba.fastjson.JSON;
import produce.entity.User;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
@RequestMapping("/boot")
public class BootController {

    @Autowired
    private AmqpAdmin amqpAdmin;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 创建交换机
     */
    @GetMapping
    public String bootTest(String msg){
        // 创建交换机
        DirectExchange directExchange = new DirectExchange("boot-direct-exchange", true, false);
        amqpAdmin.declareExchange(directExchange);

        // 创建队列
        Queue queue = new Queue("boot-queue", true, false,false);
        amqpAdmin.declareQueue(queue);

        // 创建binding绑定关系
        Binding binding = new Binding("boot-queue", Binding.DestinationType.QUEUE,"boot-direct-exchange","boot",null);
        amqpAdmin.declareBinding(binding);

        // 发送消息
        rabbitTemplate.convertAndSend("boot-direct-exchange","boot", msg);

        return "发送给boot消息成功:  "+msg;

    }


    /**
     * 创建交换机
     */
    @GetMapping("/user")
    public String bootTest(){
        // 创建交换机
        DirectExchange directExchange = new DirectExchange("boot-direct-exchange", true, false);
        amqpAdmin.declareExchange(directExchange);

        // 创建队列
        Queue queue = new Queue("boot-queue", true, false,false);
        amqpAdmin.declareQueue(queue);

        // 创建binding绑定关系
        Binding binding = new Binding("boot-queue", Binding.DestinationType.QUEUE,"boot-direct-exchange","boot",null);
        amqpAdmin.declareBinding(binding);

        // 发送消息
        User user = new User("xiaohong","234234");
        // 最后一个是指定message的id
        rabbitTemplate.convertAndSend("boot-direct-exchange","boot", JSON.toJSONString(user),new CorrelationData(UUID.randomUUID().toString()));
//        rabbitTemplate.convertAndSend("boot-direct-exchange","boot", user);

        return "发送给boot消息成功:  "+user;

    }


}
